package com.yyc.bleem.common.config;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.yyc.bleem.common.utils.JwtTokenUtil;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyc
 * 后端接口拦截器
 */
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptors()).addPathPatterns("/**");
    }

    private class MyInterceptors implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            //获取请求头中的token
            String token = request.getHeader("token");
            System.out.println("请求头中的token："+token);
            String msg = "";
            try{
                if (token == null){

                    //再返回的header中设置状态码
                    response.setHeader("code","000000");
                    response.setHeader("msg","无token！");
                    return false;
                }else {
                    //验证令牌：查看该token中有没有id 如果没异常返回值为true，则放行；否则报相应异常
                    return JwtTokenUtil.verifyToken(token);
                }
            }catch (SignatureVerificationException e){
                msg="无效签名！";
            }catch (TokenExpiredException e){
                msg="token过期!";
            }catch (AlgorithmMismatchException e){
                msg="token算法不一致！";
            }catch (Exception e){
                msg="token无效";
            }

            System.out.println(msg);
            response.setHeader("code","000000");
            response.setHeader("msg",msg);
            return false;
        }
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) {
        }
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
        }
    }


}
